/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.felipecsl.asymmetricgridview;

import ohos.agp.components.AttrSet;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentTreeObserver;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.DirectionalLayoutManager;
import ohos.agp.components.ListContainer;
import ohos.app.Context;

/**
 * 不规则网格控件
 *
 * @since 2021-04-02
 */
public class AsymmetricRecyclerView extends ListContainer implements AsymmetricView {
    private final AsymmetricViewImpl viewImpl;
    private AsymmetricRecyclerViewAdapter<?> adapter;
    private boolean isFirst = true;

    /**
     * 构造方法
     *
     * @param context 上下文
     * @param attrs 布局属性
     */
    public AsymmetricRecyclerView(Context context, AttrSet attrs) {
        super(context, attrs);
        viewImpl = new AsymmetricViewImpl(context);
        DirectionalLayoutManager layoutManager = new DirectionalLayoutManager();
        layoutManager.setOrientation(DirectionalLayout.VERTICAL);
        setLayoutManager(layoutManager);
        final ComponentTreeObserver vto = getComponentTreeObserver();
        if (vto != null) {
            vto.addTreeLayoutChangedListener(new ComponentTreeObserver.GlobalLayoutListener() {
                @Override
                public void onGlobalLayoutUpdated() {
                    LogUtil.info("GlobalLayoutListener", "onGlobalLayoutUpdated");
                    getComponentTreeObserver().removeTreeLayoutChangedListener(this);
                    viewImpl.determineColumns(getAvailableSpace());
                    if (adapter != null) {
                        adapter.recalculateItemsPerRow();
                    }
                }
            });
        }
        setEstimateSizeListener(new EstimateSizeListener() {
            @Override
            public boolean onEstimateSize(int widthMeasureSpec, int heightMeasureSpec) {
                // 执行自定义测量，返回尺寸
                viewImpl.determineColumns(getAvailableSpace());
                if (adapter != null && isFirst) {
                    isFirst = false;
                    adapter.recalculateItemsPerRow();
                }
                setEstimateSizeListener(null);
                return false;
            }
        });
    }

    @Override
    public void setItemProvider(BaseItemProvider itemProvider) {
        if (!(itemProvider instanceof AsymmetricRecyclerViewAdapter)) {
            throw new UnsupportedOperationException(
                "Adapter must be an instance of AsymmetricRecyclerViewAdapter");
        }
        super.setItemProvider(itemProvider);
        this.adapter = (AsymmetricRecyclerViewAdapter<?>) itemProvider;
        this.adapter.recalculateItemsPerRow();
    }

    @Override
    public boolean isDebugging() {
        return viewImpl.isDebugging();
    }

    @Override
    public int getNumColumns() {
        return viewImpl.getNumColumns();
    }

    @Override
    public boolean isAllowReordering() {
        return viewImpl.isAllowReordering();
    }

    @Override
    public void fireOnItemClick(int index, Component v) {
    }

    @Override
    public boolean fireOnItemLongClick(int index, Component v) {
        return false;
    }

    @Override
    public int getColumnWidth() {
        return viewImpl.getColumnWidth(getAvailableSpace());
    }

    private int getAvailableSpace() {
        return getEstimatedWidth() - getPaddingLeft() - getPaddingRight();
    }

    @Override
    public int getDividerHeight() {
        return 0;
    }

    @Override
    public int getRequestedHorizontalSpacing() {
        return viewImpl.getRequestedHorizontalSpacing();
    }

    /**
     * 请求的列数
     *
     * @param requestedColumnCount
     */
    public void setRequestedColumnCount(int requestedColumnCount) {
        viewImpl.setRequestedColumnCount(requestedColumnCount);
    }

    /**
     * 刷新数据
     */
    public void determineColumns() {
        viewImpl.determineColumns(getAvailableSpace());
    }

    /**
     * 允许重新排列
     *
     * @param isReordering 重新排列
     */
    public void setAllowReordering(boolean isReordering) {
        viewImpl.setAllowReordering(isReordering);
        if (adapter != null) {
            adapter.recalculateItemsPerRow();
        }
    }

    /**
     * 设置宽度
     *
     * @param width 宽度
     */
    public void setRequestedColumnWidth(int width) {
        viewImpl.setRequestedColumnWidth(width);
    }

    /**
     * 请求水平间距
     *
     * @param spacing
     */
    public void setRequestedHorizontalSpacing(int spacing) {
        viewImpl.setRequestedHorizontalSpacing(spacing);
    }

    /**
     * 调试设置
     *
     * @param isDebugging 调试开关
     */
    public void setDebugging(boolean isDebugging) {
        viewImpl.setDebugging(isDebugging);
    }
}
